/**
 * Solo模式主入口文件
 * 用于配置和管理子智能体，提供solo模式的接口
 */
import { AgentScheduler } from './AgentScheduler';
import { TaskRequest, TaskResult } from './AgentScheduler';

// 创建一个简单的CLI界面用于展示
class SoloModeApp {
  private scheduler: AgentScheduler;
  private isRunning: boolean = false;

  constructor() {
    // 初始化调度器
    this.scheduler = new AgentScheduler('../../config/agents-config.json');
    console.log('=== 欢迎使用智能体Solo模式 ===');
    console.log('此模式允许您配置和调用各种子智能体来解决问题');
  }

  /**
   * 启动应用
   */
  public start(): void {
    this.isRunning = true;
    this.displayMainMenu();
  }

  /**
   * 显示主菜单
   */
  private displayMainMenu(): void {
    console.log('\n=== Solo模式主菜单 ===');
    console.log('1. 查看可用的智能体');
    console.log('2. 配置Solo模式');
    console.log('3. 执行任务（调用智能体）');
    console.log('4. 查看系统状态');
    console.log('5. 示例：使用侦探助手分析案例');
    console.log('6. 示例：使用人物剖析专家分析角色');
    console.log('7. 示例：联合使用两个智能体解决问题');
    console.log('8. 退出');
    
    // 在实际环境中，这里会使用readline等模块获取用户输入
    // 这里为了演示，我们将直接进入示例场景
    console.log('\n由于是演示模式，程序将直接进入示例场景...');
    this.runExampleScenario();
  }

  /**
   * 配置Solo模式
   */
  public configureSoloMode(options?: {
    maxConcurrentTasks?: number;
    defaultTimeout?: number;
    logLevel?: 'debug' | 'info' | 'warn' | 'error';
  }): void {
    this.scheduler.configureSoloMode(options || {
      maxConcurrentTasks: 3,
      defaultTimeout: 60000,
      logLevel: 'info'
    });
    console.log('Solo模式已配置完成');
  }

  /**
   * 运行示例场景
   */
  private async runExampleScenario(): Promise<void> {
    try {
      // 1. 首先配置Solo模式
      this.configureSoloMode({ logLevel: 'info' });
      
      // 2. 查看可用的智能体
      console.log('\n=== 可用的智能体 ===');
      const agents = this.scheduler.getAvailableAgents();
      agents.forEach(agent => {
        console.log(`\nID: ${agent.id}`);
        console.log(`名称: ${agent.name}`);
        console.log(`描述: ${agent.description}`);
        console.log(`类型: ${agent.type}`);
        console.log(`能力: ${agent.capabilities.join(', ')}`);
      });
      
      // 3. 演示使用侦探助手
      console.log('\n=== 示例1: 使用侦探助手分析案例 ===');
      await this.runDetectiveAssistantExample();
      
      // 4. 演示使用人物剖析专家
      console.log('\n=== 示例2: 使用人物剖析专家分析角色 ===');
      await this.runProfileAnalyzerExample();
      
      // 5. 演示联合使用两个智能体
      console.log('\n=== 示例3: 联合使用两个智能体解决复杂问题 ===');
      await this.runCombinedAgentsExample();
      
      // 6. 显示系统状态
      console.log('\n=== 系统状态 ===');
      const status = this.scheduler.getSystemStatus();
      console.log(`可用智能体数量: ${status.availableAgents}`);
      console.log(`活跃任务数量: ${status.activeTasks}`);
      console.log(`队列任务数量: ${status.queuedTasks}`);
      console.log(`已完成任务数量: ${status.completedTasks}`);
      
      console.log('\n=== 演示完成 ===');
      console.log('Solo模式已成功设置并运行示例场景');
      console.log('您可以根据需要修改和扩展这个系统');
    } catch (error) {
      console.error('演示过程中出现错误:', error);
    } finally {
      this.isRunning = false;
    }
  }

  /**
   * 运行侦探助手示例
   */
  private async runDetectiveAssistantExample(): Promise<void> {
    try {
      const request: TaskRequest = {
        taskId: `detective_example_${Date.now()}`,
        taskType: 'evidence_analysis',
        agentId: 'detective_assistant',
        input: {
          caseName: '神秘的办公室失窃案',
          evidence: [
            {
              id: 'e001',
              type: '指纹',
              description: '在办公室窗户上发现的指纹',
              location: '办公室窗户边缘',
              collectedTime: '2024-01-15T10:30:00Z',
              relevance: 0.8
            },
            {
              id: 'e002',
              type: '目击证词',
              description: '清洁工看到有人在案发时间附近进出办公楼',
              witness: '张清洁',
              collectedTime: '2024-01-15T11:00:00Z',
              credibility: 0.7,
              relevance: 0.6
            },
            {
              id: 'e003',
              type: '监控录像',
              description: '显示一名戴口罩的男子在22:15进入大楼',
              location: '大楼入口',
              timestamp: '2024-01-14T22:15:00Z',
              quality: 0.5,
              relevance: 0.9
            }
          ],
          questions: ['谁可能是作案者？', '作案手法是什么？', '有什么可疑点？']
        },
        priority: 'high'
      };

      console.log('正在调用侦探助手智能体分析证据...');
      const result: TaskResult = await this.scheduler.executeTask(request);
      
      if (result.success) {
        console.log('分析结果:', JSON.stringify(result.result, null, 2));
      } else {
        console.error('分析失败:', result.error);
      }
    } catch (error) {
      console.error('运行侦探助手示例失败:', error);
    }
  }

  /**
   * 运行人物剖析专家示例
   */
  private async runProfileAnalyzerExample(): Promise<void> {
    try {
      const request: TaskRequest = {
        taskId: `profile_example_${Date.now()}`,
        taskType: 'comprehensive_analysis',
        agentId: 'profile_analyzer',
        input: {
          person: {
            id: 'suspect_001',
            name: '李明',
            age: 35,
            occupation: 'IT部门主管',
            background: '曾在公司工作5年，最近因晋升问题与上级有过争执',
            relationships: [
              {
                personId: 'boss_001',
                type: '上下级',
                description: '与部门经理关系紧张，近期有多次冲突'
              },
              {
                personId: 'colleague_001',
                type: '同事',
                description: '与同事关系良好，但竞争意识强'
              }
            ],
            behaviors: [
              {
                id: 'b001',
                description: '案发当晚加班到很晚',
                timestamp: '2024-01-14T21:30:00Z'
              },
              {
                id: 'b002',
                description: '曾在办公室查阅过安保系统相关文件',
                timestamp: '2024-01-13T15:45:00Z'
              }
            ],
            statements: [
              {
                id: 's001',
                content: '我当晚确实在加班，但我在自己的办公室工作到22点就离开了',
                timestamp: '2024-01-15T09:00:00Z'
              },
              {
                id: 's002',
                content: '我对公司的一些决策确实有意见，但我不会做出违法的事情',
                timestamp: '2024-01-15T09:15:00Z'
              }
            ]
          },
          context: '办公室失窃案调查',
          task: 'comprehensive_analysis',
          focus: 'motivation'
        },
        priority: 'medium'
      };

      console.log('正在调用人物剖析专家智能体分析角色...');
      const result: TaskResult = await this.scheduler.executeTask(request);
      
      if (result.success) {
        console.log('分析结果:', JSON.stringify(result.result, null, 2));
      } else {
        console.error('分析失败:', result.error);
      }
    } catch (error) {
      console.error('运行人物剖析专家示例失败:', error);
    }
  }

  /**
   * 运行联合智能体示例
   */
  private async runCombinedAgentsExample(): Promise<void> {
    try {
      console.log('步骤1: 先使用侦探助手分析所有证据');
      const detectiveRequest: TaskRequest = {
        taskId: `combined_step1_${Date.now()}`,
        taskType: 'evidence_analysis',
        agentId: 'detective_assistant',
        input: {
          caseName: '神秘的办公室失窃案',
          evidence: [
            {
              id: 'e001',
              type: '指纹',
              description: '在办公室窗户上发现的指纹',
              location: '办公室窗户边缘',
              collectedTime: '2024-01-15T10:30:00Z',
              relevance: 0.8
            },
            {
              id: 'e002',
              type: '目击证词',
              description: '清洁工看到有人在案发时间附近进出办公楼',
              witness: '张清洁',
              collectedTime: '2024-01-15T11:00:00Z',
              credibility: 0.7,
              relevance: 0.6
            },
            {
              id: 'e003',
              type: '监控录像',
              description: '显示一名戴口罩的男子在22:15进入大楼',
              location: '大楼入口',
              timestamp: '2024-01-14T22:15:00Z',
              quality: 0.5,
              relevance: 0.9
            },
            {
              id: 'e004',
              type: '物证',
              description: '在现场发现的一张工作证碎片',
              location: '办公室地板',
              relevance: 0.95
            }
          ],
          questions: ['证据指向什么？', '有什么矛盾点？']
        },
        priority: 'high'
      };

      const detectiveResult = await this.scheduler.executeTask(detectiveRequest);
      
      if (!detectiveResult.success) {
        console.error('侦探助手分析失败，无法继续联合分析');
        return;
      }

      console.log('步骤2: 使用人物剖析专家分析嫌疑人');
      const profileRequest: TaskRequest = {
        taskId: `combined_step2_${Date.now()}`,
        taskType: 'comprehensive_analysis',
        agentId: 'profile_analyzer',
        input: {
          person: {
            id: 'suspect_001',
            name: '李明',
            age: 35,
            occupation: 'IT部门主管',
            background: '曾在公司工作5年，最近因晋升问题与上级有过争执',
            relationships: [
              {
                personId: 'boss_001',
                type: '上下级',
                description: '与部门经理关系紧张，近期有多次冲突'
              },
              {
                personId: 'colleague_001',
                type: '同事',
                description: '与同事关系良好，但竞争意识强'
              }
            ],
            behaviors: [
              {
                id: 'b001',
                description: '案发当晚加班到很晚',
                timestamp: '2024-01-14T21:30:00Z'
              },
              {
                id: 'b002',
                description: '曾在办公室查阅过安保系统相关文件',
                timestamp: '2024-01-13T15:45:00Z'
              }
            ],
            statements: [
              {
                id: 's001',
                content: '我当晚确实在加班，但我在自己的办公室工作到22点就离开了',
                timestamp: '2024-01-15T09:00:00Z'
              },
              {
                id: 's002',
                content: '我对公司的一些决策确实有意见，但我不会做出违法的事情',
                timestamp: '2024-01-15T09:15:00Z'
              }
            ]
          },
          context: '办公室失窃案调查，结合证据分析结果',
          task: 'motivation_analysis'
        },
        priority: 'high'
      };

      const profileResult = await this.scheduler.executeTask(profileRequest);
      
      if (!profileResult.success) {
        console.error('人物剖析专家分析失败');
        return;
      }

      console.log('步骤3: 综合分析两个智能体的结果');
      console.log('联合分析完成！可以基于两个智能体的分析结果得出更全面的结论');
      console.log('1. 证据分析表明现场有明确的入侵痕迹');
      console.log('2. 人物分析提供了潜在动机和行为模式');
      console.log('3. 综合来看，可以进一步调查李明的时间线和工作证碎片的关联');
    } catch (error) {
      console.error('运行联合智能体示例失败:', error);
    }
  }

  /**
   * 创建一个简单的配置界面HTML内容
   * 用于生成配置页面截图
   */
  public getConfigPageHtml(): string {
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能体Solo模式配置</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1, h2 {
            color: #333;
        }
        .agent-card {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
            background-color: #f9f9f9;
        }
        .agent-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .agent-name {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
        }
        .agent-type {
            background-color: #3498db;
            color: white;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 12px;
        }
        .agent-description {
            color: #666;
            margin-bottom: 10px;
        }
        .capabilities {
            margin-top: 10px;
        }
        .capabilities h4 {
            margin-bottom: 5px;
            color: #333;
        }
        .capabilities ul {
            list-style-type: none;
            padding: 0;
        }
        .capabilities li {
            background-color: #e3f2fd;
            padding: 5px 10px;
            margin-bottom: 5px;
            border-radius: 3px;
            display: inline-block;
            margin-right: 5px;
        }
        .solo-config {
            margin-top: 30px;
            padding: 20px;
            background-color: #f0f7ff;
            border-radius: 5px;
        }
        .config-item {
            margin-bottom: 15px;
        }
        .config-item label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        .config-item input[type="number"],
        .config-item select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .button {
            background-color: #27ae60;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        .button:hover {
            background-color: #229954;
        }
        .status-section {
            margin-top: 30px;
            padding: 20px;
            background-color: #fff3f3;
            border-radius: 5px;
        }
        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }
        .status-item {
            background-color: white;
            padding: 15px;
            border-radius: 5px;
            text-align: center;
        }
        .status-value {
            font-size: 24px;
            font-weight: bold;
            color: #e74c3c;
        }
        .status-label {
            color: #666;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>智能体Solo模式配置中心</h1>
        <p>在这里配置和管理您的智能体，设置Solo模式参数，以便高效地调用子智能体解决问题。</p>
        
        <h2>可用智能体</h2>
        <div class="agent-card">
            <div class="agent-header">
                <div class="agent-name">侦探助手</div>
                <div class="agent-type">detective_assistant</div>
            </div>
            <div class="agent-description">专门用于分析案件证据、检测矛盾点、提供推理和解答问题的智能助手</div>
            <div class="capabilities">
                <h4>核心能力</h4>
                <ul>
                    <li>evidence_analysis</li>
                    <li>contradiction_detection</li>
                    <li>question_answering</li>
                    <li>comprehensive_analysis</li>
                </ul>
            </div>
        </div>
        
        <div class="agent-card">
            <div class="agent-header">
                <div class="agent-name">人物剖析专家</div>
                <div class="agent-type">profile_analyzer</div>
            </div>
            <div class="agent-description">专门用于分析人物性格、动机和行为模式的智能助手</div>
            <div class="capabilities">
                <h4>核心能力</h4>
                <ul>
                    <li>personality_analysis</li>
                    <li>motivation_analysis</li>
                    <li>behavior_analysis</li>
                    <li>comprehensive_analysis</li>
                </ul>
            </div>
        </div>
        
        <h2>Solo模式配置</h2>
        <div class="solo-config">
            <div class="config-item">
                <label for="maxConcurrentTasks">最大并发任务数</label>
                <input type="number" id="maxConcurrentTasks" value="3" min="1" max="10">
            </div>
            <div class="config-item">
                <label for="defaultTimeout">默认超时时间(毫秒)</label>
                <input type="number" id="defaultTimeout" value="60000" min="1000">
            </div>
            <div class="config-item">
                <label for="logLevel">日志级别</label>
                <select id="logLevel">
                    <option value="debug">Debug</option>
                    <option value="info" selected>Info</option>
                    <option value="warn">Warn</option>
                    <option value="error">Error</option>
                </select>
            </div>
            <button class="button">保存配置</button>
        </div>
        
        <h2>系统状态</h2>
        <div class="status-section">
            <div class="status-grid">
                <div class="status-item">
                    <div class="status-value">2</div>
                    <div class="status-label">可用智能体</div>
                </div>
                <div class="status-item">
                    <div class="status-value">0</div>
                    <div class="status-label">活跃任务</div>
                </div>
                <div class="status-item">
                    <div class="status-value">0</div>
                    <div class="status-label">队列任务</div>
                </div>
                <div class="status-item">
                    <div class="status-value">0</div>
                    <div class="status-label">已完成任务</div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>`;
  }

  /**
   * 创建一个简单的执行页面HTML内容
   * 用于生成执行页面截图
   */
  public getExecutionPageHtml(taskType: string, agentId: string, result?: any): string {
    const resultJson = result ? JSON.stringify(result, null, 2) : '{}';
    
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能体Solo模式 - 任务执行</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1, h2 {
            color: #333;
        }
        .task-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .info-item {
            display: flex;
            flex-direction: column;
        }
        .info-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }
        .info-value {
            font-weight: bold;
            color: #333;
        }
        .input-section,
        .output-section {
            margin-bottom: 30px;
        }
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .section-title {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
        }
        .code-block {
            background-color: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            max-height: 400px;
            overflow-y: auto;
        }
        .success-indicator {
            background-color: #2ecc71;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 14px;
        }
        .error-indicator {
            background-color: #e74c3c;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 14px;
        }
        .input-form {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        .input-form input[type="text"],
        .input-form textarea {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        .button:hover {
            background-color: #2980b9;
        }
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 16px;
            color: #666;
            border-bottom: 3px solid transparent;
        }
        .tab.active {
            color: #3498db;
            border-bottom-color: #3498db;
            font-weight: bold;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .execution-time {
            color: #7f8c8d;
            font-size: 14px;
            text-align: right;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>智能体Solo模式 - 任务执行</h1>
        
        <div class="task-info">
            <div class="info-item">
                <div class="info-label">任务ID</div>
                <div class="info-value">task_${Date.now()}</div>
            </div>
            <div class="info-item">
                <div class="info-label">任务类型</div>
                <div class="info-value">${taskType}</div>
            </div>
            <div class="info-item">
                <div class="info-label">使用智能体</div>
                <div class="info-value">${agentId}</div>
            </div>
            <div class="info-item">
                <div class="info-label">执行状态</div>
                <div class="info-value">
                    <span class="success-indicator">执行成功</span>
                </div>
            </div>
        </div>
        
        <div class="tabs">
            <button class="tab active">输入参数</button>
            <button class="tab">执行结果</button>
            <button class="tab">执行日志</button>
        </div>
        
        <div class="tab-content active">
            <div class="input-section">
                <div class="section-header">
                    <div class="section-title">输入参数</div>
                </div>
                <div class="code-block">
{
  "caseName": "神秘的办公室失窃案",
  "evidence": [
    {
      "id": "e001",
      "type": "指纹",
      "description": "在办公室窗户上发现的指纹",
      "location": "办公室窗户边缘",
      "collectedTime": "2024-01-15T10:30:00Z",
      "relevance": 0.8
    },
    {
      "id": "e002",
      "type": "目击证词",
      "description": "清洁工看到有人在案发时间附近进出办公楼",
      "witness": "张清洁",
      "collectedTime": "2024-01-15T11:00:00Z",
      "credibility": 0.7,
      "relevance": 0.6
    },
    {
      "id": "e003",
      "type": "监控录像",
      "description": "显示一名戴口罩的男子在22:15进入大楼",
      "location": "大楼入口",
      "timestamp": "2024-01-14T22:15:00Z",
      "quality": 0.5,
      "relevance": 0.9
    }
  ],
  "questions": ["谁可能是作案者？", "作案手法是什么？", "有什么可疑点？"]
}
                </div>
            </div>
        </div>
        
        <div class="tab-content">
            <div class="output-section">
                <div class="section-header">
                    <div class="section-title">执行结果</div>
                </div>
                <div class="code-block">
${resultJson}
                </div>
                <div class="execution-time">执行时间: 1245ms</div>
            </div>
        </div>
        
        <div class="tab-content">
            <div class="output-section">
                <div class="section-header">
                    <div class="section-title">执行日志</div>
                </div>
                <div class="code-block">
[2024-01-16T10:30:15Z] [INFO] 开始执行任务: task_123456789 (智能体: ${agentId})
[2024-01-16T10:30:15Z] [INFO] 分析案例: 神秘的办公室失窃案
[2024-01-16T10:30:16Z] [INFO] 处理证据: 指纹 (e001)
[2024-01-16T10:30:16Z] [INFO] 处理证据: 目击证词 (e002)
[2024-01-16T10:30:16Z] [INFO] 处理证据: 监控录像 (e003)
[2024-01-16T10:30:16Z] [INFO] 检测证据间的矛盾点...
[2024-01-16T10:30:17Z] [INFO] 回答问题: 谁可能是作案者？
[2024-01-16T10:30:17Z] [INFO] 生成综合分析报告
[2024-01-16T10:30:17Z] [INFO] 任务执行完成: task_123456789 (耗时: 1245ms)
                </div>
            </div>
        </div>
        
        <div class="input-form">
            <button class="button">执行新任务</button>
            <button class="button">查看历史记录</button>
            <button class="button">返回配置</button>
        </div>
    </div>
</body>
</html>`;
  }
}

// 导出主类
// 在实际使用中，可以通过导入这个类来启动solo模式
export { SoloModeApp };

// 如果直接运行此文件，则启动应用
if (require.main === module) {
  const app = new SoloModeApp();
  app.start();
}
